<?php
namespace Extend\Controller;

/**
 * 订单操作RPC接口
 * @modify trainyao 2016-05-06 创建
 */
class OrderController extends ParentController {
    protected function _initialize() {
        $this->validateUtil = new \Org\Util\Validate();
    }

    /**
     * 获取用户有效订单或历史订单
     * @modify trainyao 2016-01-11    创建
     * @modify wenhui 2017-02-20    修改 以子订单id获取订单 修改返回数据格式
     * @param intetger $userId 预定用户ID
     * @param intetger $status 0=有效订单,1=历史订单
     */
    public function userItem($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'status' => 'notnull,notempty,natureNumber',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }
        $userId = $data['userId'];
        $status = $data['status'];
        $langSet = isset($data['langSet']) ? $data['langSet'] : LANG_SET;

        $orderUserModel = D('OrderUser');
        $orderUserInfo = $orderUserModel->getInfoByUserId($userId);
        $orderInfoIds = array_column($orderUserInfo, 'orderinfo_id');
    
        // 取出用户所有的订单
        $orderLogic = A('Common/Order', 'Logic');
        try {
            //$orderRooms = $orderLogic->getSubOrder(null, null, null, null, null, null, null, null, null, null, null, true, $userId);
            $orderRooms = $orderLogic->getSubOrder(null, $orderInfoIds, null, null, null, null, null, null, null, null, null, true, null);
            $orderRooms = $orderRooms['subOrder'];

            $orderRoomSortByInfo = getArrayValueAsIndex($orderRooms, 'orderinfo_id', 'multiMode');
            $orderRooms = array();
            foreach ($orderRoomSortByInfo as $key => $subOrders) {
                // 子订单房间数据
                $orderRoomsInfo = array();
                foreach ($subOrders as $index => $subOrdersItem) {
                    $subOrderRoomItems = array(
                        'status' =>  $subOrdersItem['status'],
                        'name' =>  $subOrdersItem['name'],
                        'areaCode' =>  $subOrdersItem['areacode'],
                        'mobile' =>  $subOrdersItem['mobile'],
                        'roomInfoDelete' =>  $subOrdersItem['roomInfoDelete'],
                        'statusName' =>  $subOrdersItem['statusName'],
                        'userLoginId' =>  $subOrdersItem['user'][0]['userLoginId'],
                        'roomName' =>  $subOrdersItem['roominfo_name'],
                    );
                    array_push($orderRoomsInfo, $subOrderRoomItems);
                }

                $subOrders[0]['orderRoom'] = $orderRoomsInfo;
                array_push($orderRooms, $subOrders[0]);
            }

        } catch (\Exception $e) {
            return parent::returnJson($e->getMessage());
        }

        if (empty($orderRooms)) {
            return parent::returnJson(200, 200, array());
        }

        // 根据传入status筛选,并统计客栈ID,房间ID
        $hotelIds = array();
        $roomIds = array();
        $orderRoomIds = array();
        foreach ($orderRooms as $index => &$orderRoomItem) {
            foreach ($orderRoomItem['orderRoom'] as $key => $orderRoomItems) {
                $unset = false;
                switch ($status) {
                    case 0:
                        $unset = in_array($orderRoomItems['status'], array(ORDER_BOOKED, ORDER_PAYED, ORDER_CHECKINED, ORDER_SHOULD_CHECKOUT)) ? false : true;
                        break;
                    case 1:
                        $unset = !in_array($orderRoomItems['status'], array(ORDER_BOOKED, ORDER_PAYED, ORDER_CHECKINED, ORDER_SHOULD_CHECKOUT)) ? false : true;
                        break;
                    case 2:
                        $unset = false;
                        break;
                    case 3:
                        $unset = in_array($orderRoomItems['status'], array(ORDER_BOOKED)) ? false : true;
                        break;
                    case 4:
                        $unset = in_array($orderRoomItems['status'], array(ORDER_PAYED)) ? false : true;
                        break;
                }
                if ($unset && $userId == $orderRoomItems['userLoginId']) {
                    unset($orderRooms[$index]);
                } else {
                    $orderRoomItem['orderNumber'] = encodeOrderNumber($orderRoomItem['id'], 'MZ');
                    array_push($hotelIds, $orderRoomItem['order']['hotelentity_id']);
                    array_push($roomIds, $orderRoomItem['roominfo_id']);
                    array_push($orderRoomIds, $orderRoomItem['id']);
                }
            }
        }
        unset($orderRoomItem);

        $orderRoomIds = array_values(array_unique($orderRoomIds));
        // 补充客栈名,房型名,房间名,订单退款类型
        $hotelDetailModel = D('HotelDetail');
        $hotelIds = array_unique($hotelIds);
        $hotelDetail = $hotelDetailModel->getInfoByHotel($hotelIds);
        if (count($hotelIds) == 1) {
            $hotelDetail = array($hotelDetail);
        }
        $hotelDetail = toAssocArray($hotelDetail, 'hotelentity_id', 'name');

        $roomInfoModel = D('RoomInfo');
        $roomIds = array_unique($roomIds);
        $roomInfo = $roomInfoModel->getInfo($roomIds);
        if (count($roomIds) == 1) {
            $roomInfo = array($roomInfo);
        }
        $roomTypeIds = array_unique(array_column($roomInfo, 'roomtype_id'));
        $roomInfo = getArrayValueAsIndex($roomInfo, 'id');

        $roomTypeDetailModel = D('RoomTypeDetail');
        $roomTypeDetail = $roomTypeDetailModel->getInfoByRoomType(null, $roomTypeIds);
        if (count($roomTypeIds) == 1){
            $roomTypeDetail = array($roomTypeDetail);
        }
        $roomTypeDetail = getArrayValueAsIndex($roomTypeDetail, 'roomtype_id');

        // 获取订单退款状态
        $orderRefundModel = D('OrderRefund');
        $orderRefundInfo = $orderRefundModel->getInfoByOrder($orderRoomIds);
        if (count($orderRoomIds) == 1) {
            $orderRefundInfo = array($orderRefundInfo);
        }
        $orderRefundInfo = getArrayValueAsIndex($orderRefundInfo, 'orderroom_id');

        // 若存在已预订订单,需要获取客栈押金信息
        if (in_array(ORDER_BOOKED, array_column($orderRooms, 'status'))) {
            $hotelIds = array_column($orderRooms, 'order');
            $hotelIds = array_unique(array_column($hotelIds, 'hotelentity_id'));
            $hotelPayDetailModel = D('HotelPayDetail');
            $hotelPayDetail = $hotelPayDetailModel->getInfoByHotel($hotelIds);
            if (count($hotelIds) == 1) {
                $hotelPayDetail = array($hotelPayDetail);
            }
            $hotelPayDetail = getArrayValueAsIndex($hotelPayDetail, 'hotelentity_id');
        }

        $orderRoomModel = D('OrderRoom');
        $orderInfoModel = D('OrderInfo');
        // 组合处理数据,补充客栈名房型名房间名
        foreach ($orderRooms as &$orderRoomItem) {

            // 是否有关联订单 获取所有关联订单（即同时预定了几个房间） 
            $orderRoomAlls = $orderRoomModel->getInfoByOrder($orderRoomItem['orderinfo_id'], false);
                    
            // 预定房间数bookRoomCount
            $bookRoomCount = count($orderRoomAlls);

            $orderRoomItem['roominfo_name'] = implode(',', array_column($orderRoomAlls, 'roominfo_name'));

            $roomId = $orderRoomItem['roominfo_id'];
            $orderRoomItem['hotelName'] = empty($hotelDetail[$orderRoomItem['order']['hotelentity_id']])?'':$hotelDetail[$orderRoomItem['order']['hotelentity_id']];
            $orderRoomItem['roomName'] = $orderRoomItem['roominfo_name'];
            $orderRoomItem['roomTypeName'] = $orderRoomItem['roomtype_name'];
            $orderRoomItem['refundStatus'] = isset($orderRefundInfo[$orderRoomItem['id']]) ? $orderRefundInfo[$orderRoomItem['id']]['status'] : 0;
            $orderInfoDate = $orderInfoModel->getInfo($orderRoomItem['orderinfo_id'], false);
            if ($orderRoomInfo['status'] == ORDER_BOOKED) {
                // 未支付的订单(已预订) 订单金额
               /* $orderRoom = $orderRoomModel->getInfoByOrder($orderRoomItem['orderinfo_id'], false);
                foreach ($orderRoom as $key => $orderRoomLise) {
                    $orderRoomItem['price']  += $orderRoom[0]['payment'];
                }
                unset($orderRoomLise);*/
                $orderRoomItem['price'] = $orderInfoDate['orig'];
            } else {
                /*$orderInfoDate = $orderInfoModel->getInfo($orderRoomItem['orderinfo_id'], false);*/
                $orderRoomItem['price'] = $orderInfoDate['payment'];
            }


            $orderRoomItem['startDate'] = $orderRoomItem['startdate'];
            $orderRoomItem['endDate'] = $orderRoomItem['checkoutdate'];
            $orderRoomItem['roomTypeCoverImageUrl'] = MEIZHU_URL . $roomTypeDetail[$roomInfo[$roomId]['roomtype_id']]['coverimageurl'];
            
            foreach ($orderRoomItem['orderRoom'] as $key => &$orderRoomsItem) {
                $orderRoomsItem['statusName'] = $orderLogic->statusMap[$langSet][$orderRoomsItem['status']];
            }
            unset($orderRoomsItem);
            $orderRoomItem['currentUserLoginId'] = $userId;

            unset($orderRoomItem['order']);
            unset($orderRoomItem['enddate']);
            unset($orderRoomItem['checkoutdate']);
            unset($orderRoomItem['id']);
            unset($orderRoomItem['orderinfo_id']);
            unset($orderRoomItem['roominfo_id']);
            unset($orderRoomItem['creator']);
            //unset($orderRoomItem['night']);
            unset($orderRoomItem['realnight']);
            unset($orderRoomItem['identity']);
            //unset($orderRoomItem['createtime']);
            unset($orderRoomItem['roominfo_name']);
            unset($orderRoomItem['roomtype_name']);
            unset($orderRoomItem['payment']);
            unset($orderRoomItem['status']);
            unset($orderRoomItem['roomInfoDelete']);

        }
        unset($orderRoomItem);

        return parent::returnJson(200, 200, array_values($orderRooms));
    }

    /**
     * 获取用户单个订单信息
     * @modify trainyao 2016-01-05    创建
     * @modify wenhui 2017-02-20      返回多个房间数据
     * @modify zhangzhen 2017-03-14   会员
     * @modify zhangzhen 2017-06-02   钟点房
     */
    public function detail($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'orderNumber' => 'notnull,notempty,mzOrder',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $orderRoomId = decodeOrderNumber($data['orderNumber'], 'MZ');
        $currentUserId = $data['userId'];
        $langSet = isset($data['langSet']) ? $data['langSet'] : LANG_SET;
        $qrclietBook = $data['qrclietBook'];
        $isWechatBrowser = $data['isWechatBrowser'];

        $orderRoomModel = D('OrderRoom');
        $orderRoom = $orderRoomModel->getInfo($orderRoomId)[0];
        $orderRooms = $orderRoomModel->getInfoByOrder($orderRoom['orderinfo_id'], false);
        $orderRoomIds = array_column($orderRooms, 'id');
        $hotelPayDetailModel = D('HotelPayDetail');
        $hotelPayUsableModel = D('HotelPayUsable');
        $hotelDetailModel = D('HotelDetail');
        $orderBookLogic = A('Common/OrderBook', 'Logic');
        $orderCount = array();
        $orderUserRooms = array();

        // 全部入住条件状态
        $checkinAllEnable = false;
        // 支付宝或微信实际支付金额 和 押金
        $orderDeposit = 0;
        $orderPrice = 0;
        $orderPayPrice = 0;
        $orderReceipt = 0;
        $countRooms = 0;
        $checkinUsableInfo = null;
        $hotelPayDetail = null;
        $countMonths = 0;
        $countnights = 0;
        // 房型的义卖价
        $roomInfoModel = D('RoomInfo');
        $roomTypeModel = D('RoomType');
        $roomInfoDetail = $roomInfoModel->getInfo($orderRoom['roominfo_id']);
        $roomTypeDetail = $roomTypeModel->getInfo($roomInfoDetail['roomtype_id']);
        // 义卖价格
        $charityPrice = 0;
        //有效的房间数
        foreach ($orderRoomIds as $key => $orderRoomId) {
                
            try {
                $orderRoomInfo = $orderBookLogic->getOrderDetail($orderRoomId, $langSet);
            } catch (\Exception $e) {
                return parent::returnJson($e->getMessage());
            }

            if (is_null($checkinUsableInfo)) {
                // 是否开启办理入住条件状态
                $hotelCheckinUsableModel = D('HotelCheckinUsable');
                $checkinUsableInfo = $hotelCheckinUsableModel->getInfo($orderRoomInfo['hotelentity_id']);
            }

            if(empty($hotelPayDetail)){
                $hotelPayDetail = $hotelPayDetailModel->getInfoByHotel($orderRoomInfo['hotelentity_id']);
                //保存第一个人的订单状态
                $bookPersonStatus = $orderRoomInfo['status'];
            }
            if ($orderRoomInfo['status'] == ORDER_BOOKED) {
                // 未支付的订单(已预订), 押金为客栈设置押金 * 预订的房间数
                $orderDeposit += $hotelPayDetail['deposit'];
                $orderPrice += $orderRoomInfo['payment'];
                $countRooms++;
                // 晚数
                $countnights += $orderRoomInfo['night'];
                // 月数
                $countMonths += $orderRoomInfo['month'];
                // 已预订义卖房间数
                $charityPrice += $roomTypeDetail['charityprice'];
            } else if ($orderRoomInfo['status'] == ORDER_OUTDATED) {
                $orderReceipt = $orderRoomInfo['order']['receipt'];
                // 已支付的订单,         押金为父订单已支付押金金额
                $orderRoomInfo['deposit'] = $orderRoomInfo['order']['deposit'];
                $charityPrice = $orderRoomInfo['order']['charityprice'];
            }  else {
                $orderPrice = $orderRoomInfo['order']['orig'];
                $orderReceipt = $orderRoomInfo['order']['receipt'];
                // 已支付的订单,         押金为父订单已支付押金金额
                $orderRoomInfo['deposit'] = $orderRoomInfo['order']['deposit'];
                //$charityPrice = $orderRoomInfo['order']['charityprice'];
            }

            // 是否开启办理入住条件状态 微预定理入住状态 0=关闭 1=身份证才可以办理入住 2=美住才能办理入住 
            $checkinIDEnable = false;
            if (empty($checkinUsableInfo) || $checkinUsableInfo['type'] == 0) {
                $checkinAllEnable = false;
                $checkinIDEnable = false;
            } else if (in_array($checkinUsableInfo['type'], [2,3])) {
                $checkinAllEnable = true;
            } else if ($checkinUsableInfo['type'] == 1 && empty($orderRoomInfo['user'][$key]['identity'])) {
                $checkinIDEnable = true;
            }

            $orderUserRoomItem = array(
                'roomId' => $orderRoomInfo['roominfo_id'],
                'roomName' => $orderRoomInfo['roominfo_name'],
                'canGetCard' => $orderRoomInfo['canGetCard'],
                'orderRoomId' => $orderRoomId,
                'areaCode' => $orderRoomInfo['user'][$key]['areacode'],
                'mobile' => $orderRoomInfo['user'][$key]['mobile'],
                'name' => $orderRoomInfo['user'][$key]['name'],
                'identity' => $orderRoomInfo['user'][$key]['identity'],
                'bookUserId' => $orderRoomInfo['user'][$key]['userlogin_id'],
                'status' => $orderRoomInfo['status'],
                'statusName' => $orderRoomInfo['statusName'],
                'orig' => $orderRoomInfo['order']['orig'],
                'checkinEnable' => $checkinIDEnable,
                'orderUserId' => $orderRoomInfo['user'][$key]['id'],
            );

            array_push($orderUserRooms, $orderUserRoomItem);
        }

        $orderRoomStatus = array_column($orderUserRooms, 'status');
        if (!empty($orderRoomStatus) && in_array(ORDER_CANCELED, $orderRoomStatus)) {
            $orderPrice = $orderUserRooms[0]['orig'];
        }

        // 开启畅联代收  才计算义卖价
        $isPayUclbrt = $this->checkIsUclbrtPay($orderRoomInfo['hotelentity_id']);
        // 间夜房
        if ($orderRoomInfo['night'] > 0 && $orderRoomInfo['month'] == 0) {
            if (!empty($orderRoomStatus) && in_array(ORDER_BOOKED, $orderRoomStatus)) {
                $charityPrice = $isPayUclbrt === true ? $charityPrice * $orderRoomInfo['night'] : '0.00';
            } else if (!empty($orderRoomStatus) && in_array(ORDER_PAYED, $orderRoomStatus)) {
                $charityPrice = $orderRoomInfo['order']['charityprice'];
            } else {
                $charityPrice = $isPayUclbrt === true ? $charityPrice : '0.00';
            }
        } else {
            $charityPrice = '0.00';
        }

        // 处理数据
        $orderRoomInfo['checkinAllEnable'] = $checkinAllEnable;
        $orderRoomInfo['status'] = $bookPersonStatus;
        $orderRoomInfo['deposit'] = $orderDeposit ? $orderDeposit : $orderRoomInfo['deposit'];
        $orderRoomInfo['price'] = $orderPrice;
        $orderRoomInfo['receipt'] = $orderReceipt;
        $orderRoomInfo['orderNumber'] = $data['orderNumber'];
        $orderRoomInfo['startDate'] = $orderRoomInfo['startdate'];
        $orderRoomInfo['endDate'] = $orderRoomInfo['checkoutdate'];
        $orderRoomInfo['roomTypeName'] = $orderRoomInfo['roomtype_name'];
        $orderRoomInfo['roomName'] = $orderRoomInfo['roominfo_name'];
        $orderRoomInfo['currentUserId'] = $currentUserId;
        $orderRoomInfo['charityPrice'] = (float)$charityPrice;

        // 是否开启支付方式
        $hotelPayUsableInfo = $hotelPayUsableModel->getInfo($orderRoomInfo['hotelentity_id']);
        $currentDate = date('Y-m-d');
        $enablepay = false;
        if (($hotelPayUsableInfo['uclbrtalipayenable'] == 1 && $hotelPayUsableInfo['uclbrtalipayenddate'] >= $currentDate) || ($hotelPayUsableInfo['uclbrtwechatenable'] == 1 && $hotelPayUsableInfo['uclbrtwechatenddate'] >= $currentDate) || ($hotelPayUsableInfo['hotelalipayenable'] == 1 && $hotelPayUsableInfo['hotelalipayenddate'] >= $currentDate) || ($hotelPayUsableInfo['hotelwechatenable'] == 1 && $hotelPayUsableInfo['hotelwechatenddata'] >= $currentDate)) {
            $enablepay = true;
        }

        // 获取客栈退订规则与支付方式
        $orderRoomInfo['refundRule'] = $hotelPayDetail['refundrule'];
        $orderRoomInfo['isOffline'] = true;
        if (!empty($hotelPayDetail['type']) && $hotelPayDetail['type']>0 && $enablepay){
            $orderRoomInfo['isOffline'] = false;
        }
        // 从钥匙包进入 没有商家微信自收
        if ($qrclietBook == true) {
            if (!empty($hotelPayDetail['type']) && $hotelPayDetail['type'] == 32 && $enablepay) {
                $orderRoomInfo['isOffline'] = true;
            }
        }
        // 是否微信浏览器
        if (!$isWechatBrowser && !$qrclietBook) {
            if (!empty($hotelPayDetail['type']) && in_array($hotelPayDetail['type'], [2,32]) && $enablepay) {
                $orderRoomInfo['isOffline'] = true;
            }
        }

        $currencyLogic = A('Common/Currency', 'Logic');
        $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($orderRoomInfo['hotelentity_id'], true);
        // 默认货币不是人民币的客栈 则线下付 // 8 = 人民币
        if (!empty($hotelDefaultCurrency) && $hotelDefaultCurrency[0]['currencyId'] != 8) {
            $orderRoomInfo['isOffline'] = true;
        }

        // 获取前台电话
        $hotelDetail = $hotelDetailModel->getInfoByHotel($orderRoomInfo['hotelentity_id']);
        $orderRoomInfo['telephone'] = empty($hotelDetail['telephone'])?'':$hotelDetail['telephone'];
        $orderRoomInfo['areacode'] = empty($hotelDetail['areacode'])?'86':$hotelDetail['areacode'];
        $orderRoomInfo['mobile'] = empty($hotelDetail['mobile'])?'':$hotelDetail['mobile'];

        $orderRoomInfo['orderHotel'] = $orderRoomInfo['hotelentity_id'];
        //去除不必要的数据 
        unset($orderRoomInfo['id']);
        unset($orderRoomInfo['hotelentity_id']);
        unset($orderRoomInfo['orderinfo_id']);
        unset($orderRoomInfo['roominfo_id']);
        unset($orderRoomInfo['payment']);
        unset($orderRoomInfo['startdate']);
        unset($orderRoomInfo['enddate']);
        unset($orderRoomInfo['checkoutdate']);
        unset($orderRoomInfo['roomtype_name']);
        unset($orderRoomInfo['roominfo_name']);
        unset($orderRoomInfo['creator']);
        unset($orderRoomInfo['createtime']);
        unset($orderRoomInfo['realnight']);
        unset($orderRoomInfo['statusName']);

        $orderCount = $orderRoomInfo;
        $orderCount['user'] = $orderUserRooms;
        // 是否是 立减优惠订单
        $isMinusOrder = $orderCount['minusprice'] != '0.00' ? true : false;

        $orderRoomModel = D('OrderRoom');
        $orderInfoModel = D('OrderInfo');
        $orderDetails = $orderInfoModel->getInfo($orderRoom['orderinfo_id'],false);
        // 实际支付金额  是否是会员
        if(!empty( (float)$orderDetails['discountrule']) ){
            // 是否有立减优惠
            if (!$isMinusOrder) {
                if($orderDetails['discount']=='1'){
                    if ($orderRoomInfo['hour'] > 0) {
                        $orderCount['payPagePrice'] = $orderCount['price'] - $orderDetails['discountrule'] * $countRooms + $orderRoomInfo['deposit'];
                    } elseif ($orderRoomInfo['month'] > 0) {
                        $orderCount['payPagePrice'] = $orderCount['price'] - $orderDetails['discountrule'] * $countMonths  + $orderRoomInfo['deposit'];
                    } else {
                        // 义卖价不参与打折
                        $orderCount['payPagePrice'] = ($orderCount['price'] - $charityPrice) - $orderDetails['discountrule'] * $countnights + $orderRoomInfo['deposit'] + $charityPrice;
                    }
                }else{
                    // 义卖价不参与打折
                    $orderCount['payPagePrice'] = round(($orderCount['price'] - $charityPrice)*$orderDetails['discountrule']/10,2) + $orderRoomInfo['deposit'] + $charityPrice;
                }
            } else {
                // 优惠金额
                $orderCount['payPagePrice'] = ($orderCount['price'] - $charityPrice) - $orderRoomInfo['minusprice'] + $orderRoomInfo['deposit'] + $charityPrice;
            }
        } else {
            // 不是会员 针对间夜房是否有立减优惠 义卖价不参与打折
            if ($orderRoomInfo['night'] > 0 && $orderRoomInfo['month'] == 0 && $isMinusOrder) {
                // 立减金额方式
                $orderCount['payPagePrice'] = ($orderCount['price'] - $charityPrice) - $orderRoomInfo['minusprice'] + $orderRoomInfo['deposit'] + $charityPrice;
            } else {
                $orderCount['payPagePrice'] =  $orderCount['price'] + $orderRoomInfo['deposit'];
            }
        }

        // 优惠券优惠金额
        $orderCount['couponPrice'] = 0;
        // 是否有优惠券
        $userCouponModel = D('UserCoupon');
        $userCouponInfo = $userCouponModel->getUserCouponByOrderId($orderRoom['orderinfo_id']);
        $orderCount['couponGetNo'] = '';
        if (!empty($userCouponInfo)) {
            $orderCount['couponGetNo'] = $userCouponInfo['no'];
            $hotelCouponModel = D('HotelCoupon');
            $hotelCouponInfo = $hotelCouponModel->getCouponByIds($userCouponInfo['coupon_id']);
            if ($hotelCouponInfo[0]['type'] == 1 ) {
                $orderCount['couponPrice'] = $hotelCouponInfo[0]['minus_price'];
                // 立减
                $orderCount['payPagePrice'] = $orderCount['payPagePrice'] - $hotelCouponInfo[0]['minus_price'];
            } else if ($hotelCouponInfo[0]['type'] == 2) {
                // 押金 义卖金额 不参与优惠券打折
                $diffPayPagePrice = ($orderCount['payPagePrice'] - $orderRoomInfo['deposit'] - $charityPrice);
                $orderCount['couponPrice'] = $diffPayPagePrice  -  $diffPayPagePrice * ($hotelCouponInfo[0]['discount']/10);
                // 打折
                $orderCount['payPagePrice'] = ($orderCount['payPagePrice']-$orderRoomInfo['deposit']-$charityPrice) * ($hotelCouponInfo[0]['discount']/10) + $orderRoomInfo['deposit'] + $charityPrice;
            }
        }

        $orderCount['payPagePrice'] = number_format($orderCount['payPagePrice'], 2, '.', '');
        if ($orderReceipt != 0) {
            $orderCount['orig'] = $orderCount['receipt'] + $orderRoomInfo['deposit'];
        } else {
            $orderCount['orig'] = $orderCount['price'] + $orderRoomInfo['deposit'];
        }
        // 支付宝或微信实际支付金额 和 押金
        if (isset($data['payPagePrice'])) {
            $orderCount['roomName'] = '';
            foreach ($orderCount['user'] as $key => $orderCountUserItem) {
                if ($orderCountUserItem['status'] == ORDER_BOOKED) {
                    $orderCount['roomName'] .= ',' . $orderCountUserItem['roomName'];
                }
            }
            unset($orderCountItem);
            // 去掉‘,’
            $orderCount['roomName'] = substr($orderCount['roomName'], 1);
        } else {
            $orderCount['roomName'] = implode(',', array_column($orderCount['user'], 'roomName'));
        }

        // 在$orderCount['user']数组的 预订人 即 bookPerson = 1 
        foreach ($orderCount['user'] as $key => &$orderCountItem) {
            if ($orderCountItem['mobile'] == $orderCount['order']['mobile']) {
                $orderCountItem['bookPerson'] = 1;
                $orderCount['bookPerson'] = $orderCountItem['bookUserId'];
            } else {
                $orderCountItem['bookPerson'] = 0;
            }
        }
        unset($orderCountItem);

        unset($orderCount['canGetCard']);
        unset($orderCount['order']);
        return parent::returnJson(200, 200, $orderCount);
    }

    /**
     * 用户预定订单RPC接口
     * @modify trainyao 2016-05-06    创建
     * @modify trainyao 2016-07-07    修改为房间ID可选
     * @modify wenhui 2017-02-16    同时可以预定多个房间
     * @modify zhangzhen 2017-04-28  钟点房
     * @modify zhangzhen 2017-07-28  长租房
     * @param array $data rpc参数数组
     * @return array
     */
    public function book($data) {
        // 设置时区
        parent::switchTimeUtc($data);
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'roomType' => 'notnull,notempty,id',
            'orderDate' => 'notnull,notempty,isDate',
            'nights' => 'notnull,notempty,id',
            'hour' => 'notempty,natureNumber',
            'month' => 'notempty,natureNumber',
            'startTime' => 'notempty'
        );
        if (!is_null($data['userGetNo'])) {
            $validateRule['userGetNo'] = 'notnull,notempty,ucpOrder';
        }
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $validateRule = array(
            'mobile' => 'notnull,notempty',
            'name' => 'notnull,notempty,nameLength20',
        );
        foreach ($data['users'] as $key => $usersItem) {
            $validatePass = $this->validateUtil->validate($usersItem, $validateRule);
            $mobileValidatePass = $this->validateUtil->validate($usersItem['mobile'], 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $usersItem['areaCode'], '403,130,error'),
                ));
            if (empty($validatePass) || empty($mobileValidatePass)) {
                $message = $this->validateUtil->getError('explode', ',');
                return parent::returnJson($message['msg'][0], $message['msg'][1]);
            }
        }
        unset($userItem);

        $hotelId = $data['hotel'];
        $hotelLogic = A('Common/Hotel', 'Logic');
        // 检查客栈是否禁用,是否过期,是否打开微预定
        if (empty($hotelLogic->checkHotelStatus($hotelId))) {
            return parent::returnJson(403, 401);
        }
        if (empty($hotelLogic->checkHotelActive($hotelId))) {
            return parent::returnJson(403, 408);
        }
        $hotelBookLogic = A('Common/HotelBook', 'Logic');
        if (empty($hotelBookLogic->checkEnable($hotelId, false))) {
            return parent::returnJson(403, 409);
        }

        $roomIds = empty(array_column($data['users'], 'room')) ? null : array_column($data['users'], 'room');
        // 检查实时房态是否能预定
        $roomTypeId = $data['roomType'];
        $startDate = $data['orderDate'];
        $nights = $data['nights'];
        $endDate = $data['endDate'];
        $qrclietBook = $data['qrclietBook'];
        $isWechatBrowser = $data['isWechatBrowser'];
        try {
            if (isset($data['hour'])) {
                $hourRoomLogic = A('Common/HourRoom', 'Logic');
                $roomInfo = $hourRoomLogic->getRealtimeStatus($hotelId, $startDate, date('Y-m-d', strtotime('+1 days')), $data['hour'], false, $roomTypeId, $roomIds, true);
                if (isset($roomInfo['notCanBook'])) {
                    return parent::returnJson(403, 444, $roomInfo['notCanBook']);
                }
            } elseif(isset($data['month'])) {
                $longRoomLogic = A('Common/LongRoom', 'Logic');
                $roomInfo = $longRoomLogic->getRealtimeStatus($hotelId, $startDate, $endDate, $data['month'], false, $roomTypeId, $roomIds);
            } else {
                $roomTypeBookLogic = A('Common/RoomTypeBook', 'Logic');
                $roomInfo = $roomTypeBookLogic->getRealtimeStatus($hotelId, $startDate, $endDate, array($roomTypeId), $roomIds);
            }
        } catch (\Exception $e) {
            $errorMsg = explode(',', $e->getMessage());
            return parent::returnJson($errorMsg[0], $errorMsg[1]);
        }
        if (is_null($roomIds)) {
            if ($roomInfo[0]['rest'] == 0) {
                return parent::returnJson(403, 307);
            }
            // 顺数可以预定的房间
            foreach ($roomInfo[0]['room'] as $roomItem) {
                if ($roomItem['canBook'] == ENABLE && $roomItem['isdirty'] != ROOM_DIRTY) {
                    $roomIds = $roomItem['id'];
                    break;
                }
            }
            unset($roomItem);
        } else {
            foreach ($roomInfo[0]['room'] as $roomItem) {
                if ($roomItem['canBook'] == DISABLE && $roomItem['isdirty'] != ROOM_DIRTY) {
                    return parent::returnJson(403, 306);
                }
            }
        }
        $price = (double)$roomInfo[0]['price'];
        // 没有传roomId 返回一间可预订的房间
        $userData = array();
        foreach ($data['users'] as $key => $userItem) {
            $userOrder = array(
                'roomId' => isset($userItem['room']) ? $userItem['room'] : $roomIds,
                'orderDate' => $startDate,
                'nights' => $nights,
                'payment' => $price,
                'users' => array(array(
                    'areacode' => $userItem['areaCode'],
                    'mobile' => $userItem['mobile'],
                    'name' => $userItem['name'],
                    'identity' => $userItem['identity'],
                    'idsex' => $userItem['idsex'],
                    'idnation' => $userItem['idnation'],
                    'idaddress' => $userItem['idaddress'],
                )),
            );
            if (isset($data['hour'])) {
                $userOrder['nights'] = 0;
                $userOrder['hour'] = $data['hour'];
                $userOrder['orderDate'] = $startDate.' '.$data['startTime'].':00';
            } elseif (isset($data['month'])) {
                $userOrder['month'] = $data['month'];
            }
            array_push($userData, $userOrder);
        }
        unset($userItem);

        // 开启畅联代收  才计算义卖价
        $isPayUclbrt = $this->checkIsUclbrtPay($hotelId);
        $charityPrice = $isPayUclbrt === true ? $roomInfo[0]['charityprice'] : '0.00';
        if ($isPayUclbrt) {
            $charityPrice = $charityPrice * count($roomIds) * $nights;
        }

        $minusPrice = 0;
        //总价
        $price = (double)$roomInfo[0]['price'] * count($roomIds);

        // 获取美住在该客栈的渠道id
        $hotelChannel = $hotelLogic->getHotelChannel($hotelId, false);
        $hotelChannel = getArrayValueAsIndex($hotelChannel, 'name');
        $hotelDetail = $hotelBookLogic->getInfo($hotelId);
        $vipUserModel = D('VipUser');
        $vipUser = $vipUserModel->getInfoByMobile($hotelId, $data['users'][0]['mobile'], $data['users'][0]['areacode']?:86);
        $isVipUser = false;
        if ($vipUser) {
            $isVipUser = true;
            $vipInfoModel = D('VipInfo');
            $vipInfo = $vipInfoModel->getInfoById($vipUser['vipinfo_id']);
            $vip = [
                'orig' => $price,
                'discount' => $vipInfo['discount'],
                'discountRule' => $vipInfo['discountrule'],
            ];
            // 是否有立减优惠
            if ($roomInfo[0]['minustype'] == 0) {
                // 没立减优惠 按原来会员价打折
                if($vipInfo['discount'] == '1'){
                    if (isset($data['month'])) {
                        $price = $price - $vipInfo['discountrule'] * $data['month'] * count($roomIds);
                    } elseif ($nights > 0) {
                        $price = $price - $vipInfo['discountrule'] * $nights * count($roomIds);
                    } else {
                        $price = $price - $vipInfo['discountrule'] * count($roomIds);
                    }
                }else{
                    /*if (isset($data['month']) || isset($data['hour'])) {
                        $price = number_format($price * ($vipInfo['discountrule'] / 10),2,'.','');
                    } else {
                        $price = number_format(($price - $charityPrice) * $vipInfo['discountrule'] / 10  + $charityPrice,2,'.','');
                    }*/
                    $price = number_format($price * ($vipInfo['discountrule'] / 10),2,'.','');
                }
            } else {
                // 有立减优惠
                // 立减优惠开关，会员不同时享用两种优惠。minusenable=0(原来的会员优惠) minusenable=1(房费立减优惠)
                if ($hotelDetail['minusenable'] == 0) {
                    if($vipInfo['discount'] == '1'){
                        if (isset($data['month'])) {
                            $price = $price - $vipInfo['discountrule'] * $data['month'] * count($roomIds);
                        } elseif ($nights > 0) {
                            $price = $price - $vipInfo['discountrule'] * $nights * count($roomIds);
                        } else {
                            $price = $price - $vipInfo['discountrule'] * count($roomIds);
                        }
                    }else{
                        /*if (isset($data['month']) || isset($data['hour'])) {
                            $price = number_format($price * $vipInfo['discountrule'] / 10,2,'.','');
                        } else {
                            $price = number_format(($price - $charityPrice) * $vipInfo['discountrule'] / 10  + $charityPrice,2,'.','');
                        }*/
                        $price = number_format($price * ($vipInfo['discountrule'] / 10),2,'.','');
                    }
                } else {
                    // 针对间夜房 具体优惠金额 或 按比例优惠
                    if ($nights > 0 && !isset($data['month'])) {
                        if ($roomInfo[0]['minustype'] == 1) {
                            $price = $price - $roomInfo[0]['minusdiscount'];
                            $minusPrice = $roomInfo[0]['minusdiscount'];
                        } else if ($roomInfo[0]['minustype'] == 2) {
                            $minusPrice = ($price - $charityPrice) * ($roomInfo[0]['minusdiscount']/100);
                            $price = $price - ($price - $charityPrice) * ($roomInfo[0]['minusdiscount']/100);
                        }
                    } else {
                        //  钟点房与长租房按原来会员价打折
                        if($vipInfo['discount'] == '1'){
                            if (isset($data['month'])) {
                                $price = $price - $vipInfo['discountrule'] * $data['month'] * count($roomIds);
                            } elseif ($nights > 0) {
                                $price = $price - $vipInfo['discountrule'] * $nights * count($roomIds);
                            } else {
                                $price = $price - $vipInfo['discountrule'] * count($roomIds);
                            }
                        }else{
                            $price = number_format($price * $vipInfo['discountrule'] / 10,2,'.','');
                        }
                    }
                }
            }
            $minusInfo = array();
        } else {
            // 不是会员 是否有立减优惠
            $minusInfo = array('orig' => $price);  // 立减优惠信息
            if ($nights > 0 && !isset($data['month'])) {
                if ($roomInfo[0]['minustype'] == 1) {
                    // 具体优惠金额
                    $price = $price - $roomInfo[0]['minusdiscount'];
                    $minusPrice = $roomInfo[0]['minusdiscount'];
                } else if ($roomInfo[0]['minustype'] == 2) {
                    $minusPrice = ($price - $charityPrice) * ($roomInfo[0]['minusdiscount']/100);
                    // 按比例优惠
                    $price = $price - ($price - $charityPrice) * ($roomInfo[0]['minusdiscount']/100);
                }
            }
        }

        // 是否有优惠券
        $isOrderCoupon = false;
        $userGetNo = $data['userGetNo'];
        if (!is_null($userGetNo)) {
            $userCouponModel = D('UserCoupon');
            $getNo = decodeCouponNumber($userGetNo, 'UCP');
            $userCouponInfo = $userCouponModel->getUserCouponByGetNo($getNo);
            if (!empty($userCouponInfo)) {
                // 获取优惠券信息并过滤
                $couponData = $this->getAndFilterCouponData($userCouponInfo['coupon_id'], $roomTypeId, $isVipUser);
                if (!empty($couponData)) {
                    // 价格是否满足 优惠券满减条件
                    if (($price - $charityPrice) >= $couponData[0]['price']) {
                        // 1=满减券 2=折扣券
                        if ($couponData[0]['type'] == 1) {
                            $price = $price - $couponData[0]['minus_price'];
                        } else if ($couponData[0]['type'] == 2) {
                            $price = $price * ($couponData[0]['discount'] / 10);
                        }

                        $isOrderCoupon = true;
                    }
                } else {
                    // 优惠券暂时不可用
                    return parent::returnJson(403, 1003);
                }
            }
        }

        // 价格不能为负数
        if ((float)$price < 0) {
            return parent::returnJson(403, 1215);
        }

        // 根据当天之前是否有订单 提示不同信息
        if ($data['type'] == 1 && $data['isSplitOrder'] == 1 && $data['nights'] == 1) {
            $roomDetail = $roomInfo[0]['room'];
            $roomDetail = getArrayValueAsIndex($roomDetail, 'id');
            $returnDatas = [];
            if (is_array($roomIds)) {
                foreach ($roomIds as $key => $roomId) {
                    // 检查当天之前是否有订单
                    $isExistOrderRoom = ValidateCheckIn($hotelId, $roomId, '', $startDate);
                    if (empty($isExistOrderRoom)) {
                        $returnData = array(
                            'isExistOrderRoom' => false,
                            //'roomId' => $roomId,
                            'name' => $roomDetail[$roomId]['name'],
                        );
                    } else {
                        $returnData = array(
                            'isExistOrderRoom' => ture,
                            //'roomId' => $roomId,
                            'name' => $roomDetail[$roomId]['name'],
                        );
                    }
                    array_push($returnDatas, $returnData);
                }
                unset($roomId);
            } else {
                // 检查当天之前是否有订单
                $isExistOrderRoom = ValidateCheckIn($hotelId, $roomIds, '', $startDate);
                if (empty($isExistOrderRoom)) {
                    $returnData = array(
                        'isExistOrderRoom' => false,
                        //'roomId' => $roomIds,
                        'name' => $roomDetail[$roomIds]['name'],
                    );
                } else {
                    $returnData = array(
                        'isExistOrderRoom' => true,
                        //'roomId' => $roomIds,
                        'name' => $roomDetail[$roomIds]['name'],
                    );
                }
                array_push($returnDatas, $returnData);
            }
            return parent::returnJson(403, 1214, $returnDatas);
        }

        $roomData = ValidateCheckIn($hotelId, $roomIds);
        // 是否有脏房
        if (isset($roomData['roomInfos'])) {
            return parent::returnJson(403, 308);
        }

        // 添加数据
        $userId = $data['userId'];
        $orderRoomModel = D('OrderRoom');
        $orderRoomModel->startTrans();
        $commit = true;
        $orderLogic = A('Common/Order', 'Logic');
        try {
            $data = $orderLogic->addInfo($hotelId, $hotelChannel['美住']['id'], 0, $price, 0, '', $userData, array(), 1, ORDER_CHANGE_BOOK_WEB, 'multiMode', 0, $userId, $vip, $minusInfo, $minusPrice);
        } catch (\Exception $e) {
            $orderRoomModel->rollback();
            return parent::returnJson($e->getMessage());
        }

        // 订单根据客栈订单过期时间写入redis
        foreach ($data as $key => $dataItem) {
            $addResult = $orderRoomModel->saveInfoInRedis($hotelId, $dataItem['room'], $dataItem['id'], $hotelDetail['ordertimeout']);
            if (empty($addResult)) {
                $commit = false;
            }
        }

        if ($commit) {
            // 添加推送消息
            $this->addPushInfo($hotelId, $data);
            // 执行推送
            $result = $this->pushNewsTask($hotelId, $data[0]['room']);
        }

        // 是否开启支付方式 (是否线下付)
        $isOffline = $this->isOffline($hotelId, $qrclietBook, $isWechatBrowser);

        // 用户优惠券领取表 保存订单号
        if ($commit && !is_null($userGetNo) && $isOrderCoupon) {
            $saveResult = $userCouponModel->saveUserCouponOrderId($getNo, $data[0]['order']);
            if ($saveResult === false) {
                $commit = false;
            }
        }

        if ($commit) {
            $orderRoomModel->commit();
            // 生成订单号
            $data['orderNumber'] = encodeOrderNumber($data[0]['id'], 'MZ');
            $data['isOffline'] = $isOffline;
            if (!is_array($roomIds)) {
                $data['roomIds'] = $roomIds;
            }
            return parent::returnJson(200, 200, $data);
        } else {
            $orderRoomModel->rollback();
            return parent::returnJson(500, 508);
        }
    }

    /**
     * 添加推送消息
     * @modify wenhui 2017-03-16 创建
     * @param  int $hotelId 客栈id
     * @param  array $data 数据数组
     */
    public function addPushInfo($hotelId,$data) {
        parent::switchTimeUtc(array('hotel'=>$hotelId));
    
        $hotelNewsPushModel = D('HotelNewspush');
        $hotelNewsPushRelateModel = D('HotelNewspushRelate');
        $HotelRoomAuthorityModel = D('HotelRoomAuthority');
        $adminHotelModel = D('AdminHotel');
        $adminAuthorityModel = D('AdminAuthority');

        // 开启事务
        $hotelNewsPushModel->startTrans();
        $commit = true;

        // 只保存预订人数据
        $name = $data[0]['name'];
        $areaCode = $data[0]['areaCode'];
        $mobile = $data[0]['mobile'];
        $startdate = $data[0]['start'];
        $night = $data[0]['night'];
        $orderRoomId = $data[0]['id'];
        $roomId = $data[0]['room'];
        $roomType = $data[0]['roomtype'];
        $roomName = $data[0]['roomname'];
        $orderInfoId = $data[0]['order'];
        $hour = $data[0]['hour'];
        $month = $data[0]['month'];
        $startTime = $data[0]['starttime'];

        $type = isset($data[0]['type']) ? $data[0]['type'] : null;
        if (!is_null($type) && $type == 1) {
            // 退房时间
            $startdate = date('Y-m-d');
            $startTime = date('Y-m-d H:i:s');
            $checkoutAlert = [
                'zh_cn' => ['退房订单','晚','小时','个月'],
                'en_us' => ['Checkout Order','nights','hour','month']
            ];
        }

        // 构造推送消息
        $hoteldata = D('HotelEntity')->getInfo($hotelId);
        $alert = [
            'zh_cn' => ['预定订单','晚','小时','个月'],
            'en_us' => ['Booking Order','nights','hour','month']
        ];
        if ($hoteldata['universaltime_id'] == 5) {
            $alertNews = !is_null($type) && $type == 1 ? $checkoutAlert['zh_cn'] : $alert['zh_cn'];
        } else {
            $alertNews = !is_null($type) && $type == 1 ? $checkoutAlert['en_us'] : $alert['en_us'];
        }

        if ($hour > 0) {
            $pushNewsString = '[' . $alertNews[0] . ']' . $hoteldata['name'] . '：' . $roomName . ',' . $startTime . ',' . $hour . $alertNews[2];
        } elseif ($month>0) {
            $pushNewsString = '[' . $alertNews[0] . ']' . $hoteldata['name'] . '：' . $roomName . ',' . $startTime . ',' . $month . $alertNews[3];
        } else {
            $pushNewsString = '[' . $alertNews[0] . ']' . $hoteldata['name'] . '：' . $roomName . ',' . $startdate . ',' . $night . $alertNews[1];
        }
        // 保存推送数据
        $pushNewsId = $hotelNewsPushModel->addPushNewsInfo($hotelId, $name, $mobile, $startTime, $night, $orderRoomId, $roomType, $roomName, $roomId, $orderInfoId, $areaCode, $hour, $month, $type);
        if ($pushNewsId == false) {
            $commit = false;
        }

        if ($commit) {
            // 根据hotelId 获取超管userId
            $adminInfo = $adminHotelModel->getHotelCreator($hotelId);
            $adminloginId = $adminInfo['adminlogin_id'];
            $newsPushRelateToAdd = array(
                array(
                    'adminlogin_id' => $adminloginId,
                    'hotelnewspush_id' => $pushNewsId,
                ),
            );

            // 获取对该房间有权限的管理员id 并保存推送关联数据
            $HotelRoomAuthorityInfo = $HotelRoomAuthorityModel->getInfoByHotelRoom($hotelId, $roomId);
            if (!empty($HotelRoomAuthorityInfo)) {
                foreach ($HotelRoomAuthorityInfo as $key => $roomAuthority) {
                    // 有查看订单权限
                    $authorityResult = $adminAuthorityModel->getInfoByAdminHotelAuthority($roomAuthority['adminlogin_id'], $hotelId, 3);
                    if (!empty($authorityResult)) {
                        $newsPushRelateToAddItem = array(
                            'adminlogin_id' => $roomAuthority['adminlogin_id'],
                            'hotelnewspush_id' => $pushNewsId,
                        );

                        array_push($newsPushRelateToAdd, $newsPushRelateToAddItem);
                    }
                }
                unset($roomAuthority);
            }

            $result = $hotelNewsPushRelateModel->addPushNewsRelateInfo($hotelId, $newsPushRelateToAdd);
            if ($result) {
                // 是否开启美住app功能
                $hotelLogic = A('Common/Hotel', 'Logic');
                $resultEnable = $hotelLogic->checkHotelAppEnable($hotelId);
                if ($resultEnable) {
                    // 写入redis 在meizhu\src\Pms\meizhu\Cli\Controller\SocketController.class.php  function startNewsPush 美住app推送消息使用
                    $this->redisUtil = new \Org\Util\RedisHelper(null, null, 'meizhu');
                    $this->redisUtil->db(C('REDIS_ORDER_PUSH_DB'))->table('newsPush');
                    $newsPushRelateToAdd = array_column($newsPushRelateToAdd, 'adminlogin_id');
                    $addResult = $this->redisUtil->hMSet($hotelId . '_' . $roomId, $newsPushRelateToAdd);
                    $addResult = $this->redisUtil->hMSet($hotelId . '_' . $roomId . ':pushNotice', array($pushNewsString));
                }
            }
            if ($result == false) {
               $commit = false;
            }
        }

        if ($commit) {
           $hotelNewsPushModel->commit();
           return true;
        } else {
           $hotelNewsPushModel->rollback();
           return false;
        }
    }

    /**
     * 用户执行支付宝支付
     * @modify trainyao 2016-05-16 创建
     * @modify wenhui 2017-02-28 可以支付多个子订单
     * @modify zhangzhen 2017-03-14 添加会员
     */
    public function aliPay($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'aliPayData' => 'notnull,notempty',
            'orderNumber' => 'notnull,notempty,mzOrder',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $orderNumber = $data['orderNumber'];

        // 开启事务
        $fileLogUtil = new \Org\Util\FileLog();
        $orderRoomModel = D('OrderRoom');
        $orderRoomModel->startTrans();
        $commit = true;

        $aliPayData = $data['aliPayData'];
        $totalFee = isset($aliPayData['total_fee']) ? $aliPayData['total_fee'] : 0;

        // 判断支付是否成功
        $tradeStatus = isset($aliPayData['trade_status']) ? $aliPayData['trade_status'] : '';
        if (!empty($tradeStatus) && !in_array($tradeStatus, array('TRADE_FINISHED', 'TRADE_SUCCESS'))) {
            $fileLogUtil->write('支付宝回调状态为支付失败:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/AliPay/" . date('Y-m-d') . "_error.log");
            $orderRoomModel->rollback();
            return parent::returnJson(500, 500);
        }

        // 获取订单信息,判断是否需要执行修改订单,若需要,执行修改
        $orderRoomId = decodeOrderNumber($orderNumber, 'MZ');

        $orderRoomModel = D('OrderRoom');
        $orderRoom = $orderRoomModel->getInfo($orderRoomId)[0];
        $orderRooms = $orderRoomModel->getInfoByOrder($orderRoom['orderinfo_id'], false);
        $orderRoomIds = array_column($orderRooms, 'id');

        // 是否有优惠券
        $userCouponModel = D('UserCoupon');
        $userCouponInfo = $userCouponModel->getUserCouponByOrderId($orderRoom['orderinfo_id']);
        $couponGetNo = null;
        if (!empty($userCouponInfo)) {
            $couponGetNo = $userCouponInfo['no'];
        }

        // 获取房型义卖值
        $roomInfoDetail = D('RoomInfo')->getInfo($orderRoom['roominfo_id']);
        $roomTypeDetail = D('RoomType')->getInfo($roomInfoDetail['roomtype_id']);
        $charityPrice = $roomTypeDetail['charityprice'];
        // 是否是间夜房订单
        $isRoomNight = $orderRoom['hour'] != 0 || $orderRoom['month'] != 0 ? false : true;

        $orderBookLogic = A('Common/OrderBook', 'Logic');
        try {
            // 获取子订单数据 组装数据格式
            $orderDetails = array();
            // 已预订房间数
            $orderBookedRooms = 0;
            $deposit = 0;
            $orderRoomInfo = $orderBookLogic->getOrderDetail($orderRoomId);
            // 获取客栈押金
            $hotelPayDetailModel = D('HotelPayDetail');
            $hotelPayDetail = $hotelPayDetailModel->getInfoByHotel($orderRoomInfo['order']['hotelentity_id']);

            foreach ($orderRoomIds as $key => $orderRoomIdItem) {
                $orderRoomInfos = $orderBookLogic->getOrderDetail($orderRoomIdItem);
                if ($orderRoomInfos['status'] == ORDER_BOOKED) {
                    $orderBookedRooms ++;
                    // 子订单总押金 
                    $deposit += $hotelPayDetail['deposit'];
                    $orderDetailItem = array(
                        'orderRoomId' => $orderRoomInfos['id'],
                        'orderDate' => empty($orderRoomInfos['hour']) ? substr($orderRoomInfos['startdate'], 0, 10) : $orderRoomInfos['startdate'],
                        'roomId' => $orderRoomInfos['roominfo_id'],
                        'nights' => $orderRoomInfos['realnight'],
                        'hour' => $orderRoomInfos['hour'],
                        'payment' => $orderRoomInfos['payment'],
                        'users' => array(),
                    );
                    array_push($orderDetails, $orderDetailItem);
                }
            }
            unset($orderRoomIdItem);

            // 畅联代收 才计算义卖价 (针对间夜房)
            $aliPayConfig = C('ALIPAY');
            // 晚数 
            $nights = !empty($orderDetails) ? $orderDetails[0]['nights'] : 0;
            $charityPrice = $aliPayConfig['seller_email'] == $aliPayData['seller_email'] ? $charityPrice * $orderBookedRooms * $nights : '0.00';
            // 订单义卖值 (针对间夜房)
            $charityPrice = $isRoomNight === true ? number_format($charityPrice, 2 ,'.', '') : '0.00';
            
            // 子订单共同数据
            if ($orderRoomInfo['status'] == ORDER_BOOKED) {
                $receipt = (double)$totalFee - (double)$deposit;

                // 获取支付宝支付在该客栈的支付方式id
                $hotelLogic = A('Common/Hotel', 'Logic');
                $hotelPay = $hotelLogic->getHotelPay($orderRoomInfo['order']['hotelentity_id'], false);
                $hotelPay = getArrayValueAsIndex($hotelPay, 'name');
                $hotelPayId = $hotelPay['支付宝支付']['id'];

                foreach ($orderDetails as $key => &$orderDetailsItem) {
                    foreach ($orderRoomInfo['user'] as $orderUserItem) {
                        array_push($orderDetailsItem['users'], array(
                            'name' => $orderUserItem['name'],
                            'mobile' => $orderUserItem['mobile'],
                            'identity' => $orderUserItem['identity'],
                            'orderUser' => $orderUserItem['id'],
                        ));
                    }
                    unset($orderUserItem);
                }
                unset($orderDetailsItem);

                // 获取客栈默认货币
                $currencyLogic = A('Common/Currency', 'Logic');
                $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($orderRoomInfo['order']['hotelentity_id'], true);
                $currencyId = !empty($hotelDefaultCurrency) ? $hotelDefaultCurrency[0]['currencyId'] : 8 ; // 8 = 人民币

                $receives = array(array(
                    'category' => PAY_CHANGE_RECEIPT,
                    'type' => $hotelPayId,
                    'value' => $receipt,
                    'transBeforeValue' => $receipt,
                    'transCurrencyId' => $currencyId,
                ));
                if ($deposit != 0) {
                    array_push($receives, array(
                        'category' => PAY_CHANGE_DEPOSIT,
                        'type' => $hotelPayId,
                        'value' => $deposit,
                        'transBeforeValue' => $deposit,
                        'transCurrencyId' => $currencyId,
                    ));
                }
                //找出vip信息
                $orderInfoModel = D('OrderInfo');
                $orderVip = $orderInfoModel->getInfo($orderRoomInfo['order']['id'], false);
                $vip['discountRule'] = $orderVip['discountrule'];
                $vip['discount'] = $orderVip['discount'];
                $orderLogic = A('Common/Order', 'Logic');
                $payResult = $orderLogic->saveInfo($orderRoomInfo['order']['hotelentity_id'], $orderRoomInfo['order']['id'], $orderRoomInfo['order']['hotelchannel_id'], $deposit, $receipt, null, $orderDetails, $receives, ORDER_CHANGE_BOOK_WEB, $orderRoomInfo['order']['userlogin_id'], 'multiTransMode', $vip, $charityPrice, null, null, $couponGetNo);
                if (empty($payResult)) {
                    $commit = false;
                }
            } else {
                // 传过来的订单号已支付过或处于其他状态
                $fileLogUtil->write($orderRoomInfo['status'] . '状态子订单非法请求支付接口:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/AliPay/" . date('Y-m-d') . "_error.log");
            }
        } catch (\Exception $e) {
            $orderRoomModel->rollback();
            return parent::returnJson($e->getMessage());
        }

        if ($commit) {
            // 查询是否已经存在支付宝支付记录,并记录数据
            $orderPayInfoModel = D('OrderPayInfo');
            $orderPayInfo = $orderPayInfoModel->getInfoByOrderMethod($orderRoomId, ORDER_PAY_ALI);
            if (empty($orderPayInfo)) {
                $tradeNo = isset($aliPayData['trade_no']) ? $aliPayData['trade_no'] : '';
                $notifyId = isset($aliPayData['notify_id']) ? $aliPayData['notify_id'] : '';
                $notifyTime = isset($aliPayData['notify_time']) ? $aliPayData['notify_time'] : '';
                $buyerEmail = isset($aliPayData['buyer_email']) ? $aliPayData['buyer_email'] : '';
                $buyerId = isset($aliPayData['buyer_id']) ? $aliPayData['buyer_id'] : '';

                // 判断卖家是否畅联代收还是商家自收,按情况插入类型
                //$aliPayConfig = C('ALIPAY');
                $type = $aliPayConfig['seller_email'] == $aliPayData['seller_email'] ? PAY_TYPE_UCLBRT_ALIPAY : PAY_TYPE_HOTEL_ALIPAY;
                $payResult = $orderPayInfoModel->addInfo($orderRoomInfo['order']['hotelentity_id'], $orderRoomId, ORDER_PAY_ALI, $tradeNo, $orderNumber, $buyerEmail, $buyerId, $totalFee, $notifyTime, null, null, null, 'notifyId:' . $notifyId, $type);
                if (empty($payResult)) {
                    $commit = false;
                }
            } else {
                $fileLogUtil->write('已记录支付记录子订单重复请求支付接口:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/AliPay/" . date('Y-m-d') . "_error.log");
            }
        }

        if ($commit) {
            $orderRoomModel->commit();
            return parent::returnJson(200, 200);
        } else {
            $orderRoomModel->rollback();
            $fileLogUtil->write('支付宝支付修改数据失败:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/AliPay/" . date('Y-m-d') . "_error.log");
            return parent::returnJson(500, 500);
        }
    }

    /**
     * 用户执行支付宝支付
     * @modify trainyao 2016-05-16 创建
     * @modify wenhui 2017-02-28 可以支付多个子订单
     * @modify zhangzhen 2017-03-14 添加会员
     */
    public function chargeAliPay($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'vipUserId' => 'notnull,notempty,id',
            'aliPayData' => 'notnull,notempty',
            'orderNumber' => 'notnull,notempty',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $orderNumber = $data['orderNumber'];
        $vipUserId = $data['vipUserId'];

        // 开启事务
        $fileLogUtil = new \Org\Util\FileLog();
        $vipUserModel = D('VipUser');
        $vipUserModel->startTrans();
        $commit = true;

        $aliPayData = $data['aliPayData'];
        $totalFee = isset($aliPayData['total_fee']) ? $aliPayData['total_fee'] : 0;

        // 判断支付是否成功
        $tradeStatus = isset($aliPayData['trade_status']) ? $aliPayData['trade_status'] : '';
        if (!empty($tradeStatus) && !in_array($tradeStatus, array('TRADE_FINISHED', 'TRADE_SUCCESS'))) {
            $fileLogUtil->write('支付宝回调状态为支付失败:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/AliPay/" . date('Y-m-d') . "_error.log");
            $vipUserModel->rollback();
            return parent::returnJson(500, 500);
        }

        // 获取vip信息
        $vipUserInfo = $vipUserModel->getInfoById($vipUserId);
        $hotelId = $vipUserInfo['hotelentity_id'];

        // 获取支付宝支付在该客栈的支付方式id
        $hotelLogic = A('Common/Hotel', 'Logic');
        $hotelPay = $hotelLogic->getHotelPay($hotelId, false);
        $hotelPay = getArrayValueAsIndex($hotelPay, 'name');
        $hotelPayId = $hotelPay['支付宝支付']['id'];

        if ($commit) {
            // 查询是否已经存在支付宝支付记录,并记录数据
            $vipCardPayInfoModel = D('VipCardPayInfo');
            $vipCardPayInfo = $vipCardPayInfoModel->getInfoByOrderNumberMethod($orderNumber, ORDER_PAY_ALI);
            if (empty($vipCardPayInfo)) {
                $tradeNo = isset($aliPayData['trade_no']) ? $aliPayData['trade_no'] : '';
                $notifyId = isset($aliPayData['notify_id']) ? $aliPayData['notify_id'] : '';
                $notifyTime = isset($aliPayData['notify_time']) ? $aliPayData['notify_time'] : '';
                $buyerEmail = isset($aliPayData['buyer_email']) ? $aliPayData['buyer_email'] : '';
                $buyerId = isset($aliPayData['buyer_id']) ? $aliPayData['buyer_id'] : '';

                // 卖家是商家自收
                $type = PAY_TYPE_HOTEL_ALIPAY;
                $payResult = $vipCardPayInfoModel->addInfo($hotelId, $vipUserId, ORDER_PAY_ALI, $tradeNo, $orderNumber, $buyerEmail, $buyerId, $totalFee, $notifyTime, null, null, null, 'notifyId:' . $notifyId, $type);
                if (empty($payResult)) {
                    $commit = false;
                }
            } else {
                $fileLogUtil->write('已记录支付记录订单号重复请求支付接口:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/AliPay/" . date('Y-m-d') . "_error.log");
                $commit = false;
            }
        }

        if ($commit) {
            $customerLogic = A('Common/Customer', 'Logic');
            $vipCardInfos = $customerLogic->setVipUserCard($hotelId, $vipUserId, $totalFee, $hotelPayId, '', 1, 2);
            if ($vipCardInfos == false) {
                $commit = false;
            }
        }

        if ($commit) {
            $vipUserModel->commit();
            return parent::returnJson(200, 200);
        } else {
            $vipUserModel->rollback();
            $fileLogUtil->write('支付宝支付修改数据失败:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/AliPay/" . date('Y-m-d') . "_error.log");
            return parent::returnJson(500, 500);
        }
    }

    /**
     * 用户执行微信支付
     * @modify trainyao 2016-05-16 创建
     * @modify wenhui 2017-02-28 可以支付多个子订单
     */
    public function chargeWechatPay($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'wechatPayData' => 'notnull,notempty',
            'orderNumber' => 'notnull,notempty',
            'vipUserId' => 'notnull,notempty,id',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $orderNumber = $data['orderNumber'];
        $vipUserId = $data['vipUserId'];

        // 开启事务
        $fileLogUtil = new \Org\Util\FileLog();
        $vipUserModel = D('VipUser');
        $vipUserModel->startTrans();
        $commit = true;

        $wechatPayData = $data['wechatPayData'];
        $totalFee = isset($wechatPayData['total_fee']) ? $wechatPayData['total_fee'] : 0;
        $totalFee = round(($totalFee / 100), 2);

        // 判断支付是否成功
        $returnCode = isset($wechatPayData['return_code']) ? $wechatPayData['return_code'] : '';
        if (!empty($returnCode) && !in_array($returnCode, array('SUCCESS'))) {
            $fileLogUtil->write('微信回调状态为支付失败:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/WechatPay/" . date('Y-m-d') . "_error.log");
            $vipUserModel->rollback();
            return parent::returnJson(500, 500);
        }

        // 获取vip信息
        $vipUserInfo = $vipUserModel->getInfoById($vipUserId);
        $hotelId = $vipUserInfo['hotelentity_id'];
  
        // 获取微信支付在该客栈的支付方式id
        $hotelLogic = A('Common/Hotel', 'Logic');
        $hotelPay = $hotelLogic->getHotelPay($hotelId, false);
        $hotelPay = getArrayValueAsIndex($hotelPay, 'name');
        $hotelPayId = $hotelPay['微信支付']['id'];

        if ($commit) {
            // 查询是否已经存在微信支付记录,并记录数据
            $vipCardPayInfoModel = D('VipCardPayInfo');
            $vipCardPayInfo = $vipCardPayInfoModel->getInfoByOrderNumberMethod($orderNumber, ORDER_PAY_WECHAT);
            if (empty($vipCardPayInfo)) {
                $tradeNo = isset($wechatPayData['transaction_id']) ? $wechatPayData['transaction_id'] : '';
                $notifyTime = isset($wechatPayData['time_end']) ? date('Y-m-d H:i:s', strtotime($wechatPayData['time_end'])) : '';
                $buyer = isset($wechatPayData['openid']) ? substr($wechatPayData['openid'], 0, 50) : '';
                $isSubscribe = isset($wechatPayData['is_subscribe']) ? $wechatPayData['is_subscribe'] : '';
                $isSubscribe = $isSubscribe == 'Y' ? ENABLE : DISABLE;
                $tradeType = isset($wechatPayData['trade_type']) ? $wechatPayData['trade_type'] : '';
                $type = PAY_TYPE_HOTEL_WECHAT;

                $payResult = $vipCardPayInfoModel->addInfo($hotelId, $vipUserId, ORDER_PAY_WECHAT, $tradeNo, $orderNumber, $buyer, '', $totalFee, $notifyTime, null, $isSubscribe, $tradeType, '', $type);
                if (empty($payResult)) {
                    $commit = false;
                }
            } else {
                $fileLogUtil->write('已记录支付记录订单号重复请求支付接口:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/WechatPay/" . date('Y-m-d') . "_error.log");
                $commit = false;
            }
        }

        if ($commit) {
            $customerLogic = A('Common/Customer', 'Logic');
            $vipCardInfos = $customerLogic->setVipUserCard($hotelId, $vipUserId, $totalFee, $hotelPayId, '', 1, 2);
            if ($vipCardInfos == false) {
                $commit = false;
            }
        }

        if ($commit) {
            $vipUserModel->commit();
            return parent::returnJson(200, 200);
        } else {
            $vipUserModel->rollback();
            $fileLogUtil->write('微信支付修改数据失败:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/WechatPay/" . date('Y-m-d') . "_error.log");
            return parent::returnJson(500, 500);
        }
    }

    /**
     * 用户执行微信支付
     * @modify trainyao 2016-05-16 创建
     * @modify wenhui 2017-02-28 可以支付多个子订单
     */
    public function wechatPay($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'wechatPayData' => 'notnull,notempty',
            'orderNumber' => 'notnull,notempty,mzOrder',
            'userId' => 'notnull,notempty,id',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $orderNumber = $data['orderNumber'];

        // 开启事务
        $fileLogUtil = new \Org\Util\FileLog();
        $orderRoomModel = D('OrderRoom');
        $orderRoomModel->startTrans();
        $commit = true;

        $wechatPayData = $data['wechatPayData'];
        $totalFee = isset($wechatPayData['total_fee']) ? $wechatPayData['total_fee'] : 0;
        $totalFee = round(($totalFee / 100), 2);

        // 判断支付是否成功
        $returnCode = isset($wechatPayData['return_code']) ? $wechatPayData['return_code'] : '';
        if (!empty($returnCode) && !in_array($returnCode, array('SUCCESS'))) {
            $fileLogUtil->write('微信回调状态为支付失败:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/WechatPay/" . date('Y-m-d') . "_error.log");
            $orderRoomModel->rollback();
            return parent::returnJson(500, 500);
        }

        // 获取订单信息,判断是否需要执行修改订单,若需要,执行修改
        $orderRoomId = decodeOrderNumber($orderNumber, 'MZ');

        $orderRoom = $orderRoomModel->getInfo($orderRoomId)[0];
        $orderRooms = $orderRoomModel->getInfoByOrder($orderRoom['orderinfo_id'], false);
        $orderRoomIds = array_column($orderRooms, 'id');

        // 是否有优惠券
        $userCouponModel = D('UserCoupon');
        $userCouponInfo = $userCouponModel->getUserCouponByOrderId($orderRoom['orderinfo_id']);
        $couponGetNo = null;
        if (!empty($userCouponInfo)) {
            $couponGetNo = $userCouponInfo['no'];
        }

        // 获取房型义卖值
        $roomInfoDetail = D('RoomInfo')->getInfo($orderRoom['roominfo_id']);
        $roomTypeDetail = D('RoomType')->getInfo($roomInfoDetail['roomtype_id']);
        $charityPrice = $roomTypeDetail['charityprice'];
        // 是否是间夜房订单
        $isRoomNight = $orderRoom['hour'] != 0 || $orderRoom['month'] != 0 ? false : true;

        $userId = $data['userId'];
        $orderBookLogic = A('Common/OrderBook', 'Logic');
        try {
            // 获取子订单数据 组装数据格式
            $orderDetails = array();
            // 已预订房间数
            $orderBookedRooms = 0;
            $deposit = 0;
            $orderRoomInfo = $orderBookLogic->getOrderDetail($orderRoomId);
            // 获取客栈押金
            $hotelPayDetailModel = D('HotelPayDetail');
            $hotelPayDetail = $hotelPayDetailModel->getInfoByHotel($orderRoomInfo['order']['hotelentity_id']);

            foreach ($orderRoomIds as $key => $orderRoomIdItem) {
                $orderRoomInfos = $orderBookLogic->getOrderDetail($orderRoomIdItem);
                if ($orderRoomInfos['status'] == ORDER_BOOKED || $orderRoomInfos['status'] == ORDER_OUTDATED) {
                    $orderBookedRooms ++;
                    // 子订单总押金
                    $deposit += $hotelPayDetail['deposit'];
                    $orderDetailItem = array(
                        'orderRoomId' => $orderRoomInfos['id'],
                        'orderDate' =>  empty($orderRoomInfos['hour']) ? substr($orderRoomInfos['startdate'], 0, 10) : $orderRoomInfos['startdate'],
                        'roomId' => $orderRoomInfos['roominfo_id'],
                        'nights' => $orderRoomInfos['realnight'],
                        'hour' => $orderRoomInfos['hour'],
                        'payment' => $orderRoomInfos['payment'],
                        'users' => array(),
                    );
                    array_push($orderDetails, $orderDetailItem);
                }

                // 校验调用的是否订单预订者
                if ($orderRoomInfo['order']['userlogin_id'] != $userId) {
                    return parent::returnJson(403, 202);
                }
            }
            unset($orderRoomIdItem);

            // 晚数 
            $nights = !empty($orderDetails) ? $orderDetails[0]['nights'] : 0;
            // 畅联代收才计算义卖价 (针对间夜房)
            $wechatPayConfig = C('WECHAT_PAY_CONFIG');
            $qrWechatPayConfig = C('QR_WECHAT_PAY_CONFIG');
            $charityPrice = ($wechatPayConfig['appid'] == $wechatPayData['appid'] && $wechatPayConfig['mchid'] == $wechatPayData['mch_id']) || ($qrWechatPayConfig['appid'] == $wechatPayData['appid'] && $qrWechatPayConfig['mchid'] == $wechatPayData['mch_id']) ? $charityPrice * $orderBookedRooms * $nights : '0.00';
            // 订单义卖值 (针对间夜房)
            $charityPrice = $isRoomNight === true ? number_format($charityPrice, 2 ,'.', '') : '0.00';
            // 子订单共同数据
            $receipt = (double)$totalFee - (double)$deposit;
            
            // 获取微信支付在该客栈的支付方式id
            $hotelLogic = A('Common/Hotel', 'Logic');
            $hotelPay = $hotelLogic->getHotelPay($orderRoomInfo['order']['hotelentity_id'], false);
            $hotelPay = getArrayValueAsIndex($hotelPay, 'name');
            $hotelPayId = $hotelPay['微信支付']['id'];

            foreach ($orderDetails as $key => &$orderDetailsItem) {
                foreach ($orderRoomInfo['user'] as $orderUserItem) {
                    array_push($orderDetailsItem['users'], array(
                        'name' => $orderUserItem['name'],
                        'mobile' => $orderUserItem['mobile'],
                        'identity' => $orderUserItem['identity'],
                        'orderUser' => $orderUserItem['id'],
                    ));
                }
                unset($orderUserItem);
            }
            unset($orderDetailsItem);

            // 获取客栈默认货币
            $currencyLogic = A('Common/Currency', 'Logic');
            $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($orderRoomInfo['order']['hotelentity_id'], true);
            $currencyId = !empty($hotelDefaultCurrency) ? $hotelDefaultCurrency[0]['currencyId'] : 8 ; // 8 = 人民币

            $receives = array(array(
                'category' => PAY_CHANGE_RECEIPT,
                'type' => $hotelPayId,
                'value' => $receipt,
                'transBeforeValue' => $receipt,
                'transCurrencyId' => $currencyId,
            ));
            if ($deposit != 0) {
                array_push($receives, array(
                    'category' => PAY_CHANGE_DEPOSIT,
                    'type' => $hotelPayId,
                    'value' => $deposit,
                    'transBeforeValue' => $deposit,
                    'transCurrencyId' => $currencyId,
                ));
            }
            $orderLogic = A('Common/Order', 'Logic');
            $payResult = $orderLogic->saveInfo($orderRoomInfo['order']['hotelentity_id'], $orderRoomInfo['order']['id'], $orderRoomInfo['order']['hotelchannel_id'], $deposit, $receipt, null, $orderDetails, $receives, ORDER_CHANGE_BOOK_WEB, $orderRoomInfo['order']['userlogin_id'], 'multiTransMode', null, $charityPrice, null, null, $couponGetNo);
            if (empty($payResult)) {
                $commit = false;
                // 传过来的订单号已支付过或处于其他状态
                $fileLogUtil->write(json_encode($orderRoomInfo) . ' 状态子订单非法请求支付接口:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/WechatPay/" . date('Y-m-d') . "_error.log");
            }
                
        } catch (\Exception $e) {
            $orderRoomModel->rollback();
            return parent::returnJson($e->getMessage());
        }

        if ($commit) {
            // 查询是否已经存在微信支付记录,并记录数据
            $orderPayInfoModel = D('OrderPayInfo');
            $orderPayInfo = $orderPayInfoModel->getInfoByOrderMethod($orderRoomId, ORDER_PAY_WECHAT);
            if (empty($orderPayInfo)) {
                $tradeNo = isset($wechatPayData['transaction_id']) ? $wechatPayData['transaction_id'] : '';
                $notifyTime = isset($wechatPayData['time_end']) ? date('Y-m-d H:i:s', strtotime($wechatPayData['time_end'])) : '';
                $buyer = isset($wechatPayData['openid']) ? substr($wechatPayData['openid'], 0, 50) : '';
                $isSubscribe = isset($wechatPayData['is_subscribe']) ? $wechatPayData['is_subscribe'] : '';
                $isSubscribe = $isSubscribe == 'Y' ? ENABLE : DISABLE;
                $tradeType = isset($wechatPayData['trade_type']) ? $wechatPayData['trade_type'] : '';

                // 判断卖家是否畅联代收还是商家自收,按情况插入类型
                //$wechatPayConfig = C('WECHAT_PAY_CONFIG');
                //$qrWechatPayConfig = C('QR_WECHAT_PAY_CONFIG');
                $type = ($wechatPayConfig['appid'] == $wechatPayData['appid'] && $wechatPayConfig['mchid'] == $wechatPayData['mch_id']) || ($qrWechatPayConfig['appid'] == $wechatPayData['appid'] && $qrWechatPayConfig['mchid'] == $wechatPayData['mch_id']) ? PAY_TYPE_UCLBRT_WECHAT : PAY_TYPE_HOTEL_WECHAT;
                // 判断是微信app起调微信支付还是钥匙包app起调微信支付
                $wechatPayApp = $qrWechatPayConfig['appid'] == $wechatPayData['appid'] && $qrWechatPayConfig['mchid'] == $wechatPayData['mch_id'] ? PAY_QRCLIENT_APP : PAY_WECHAT_APP;
                $payResult = $orderPayInfoModel->addInfo($orderRoomInfo['order']['hotelentity_id'], $orderRoomId, ORDER_PAY_WECHAT, $tradeNo, $orderNumber, $buyer, '', $totalFee, $notifyTime, null, $isSubscribe, $tradeType, '', $type, $wechatPayApp);
                if (empty($payResult)) {
                    $commit = false;
                }
            } else {
                $fileLogUtil->write('已记录支付记录子订单重复请求支付接口:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/WechatPay/" . date('Y-m-d') . "_error.log");
            }
        }

        if ($commit) {
            $orderRoomModel->commit();
            return parent::returnJson(200, 200);
        } else {
            $orderRoomModel->rollback();
            $fileLogUtil->write('支付宝支付修改数据失败:' . $orderNumber, 1,  RUNTIME_PATH . "/Logs/Home/WechatPay/" . date('Y-m-d') . "_error.log");
            return parent::returnJson(500, 500);
        }
    }

    /**
     * 用户执行会员卡支付
     * @modify wenhui 2018-01-16
     */
    public function vipCardPay($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'orderNumber' => 'notnull,notempty,mzOrder',
            'totalFee' => 'notnull,notempty,decimal8_2',
        );

        if (!empty($data['couponGetNo'])) {
            $validateRule['couponGetNo'] = 'notnull,notempty,ucpOrder';
        }
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        // 开启事务
        $orderRoomModel = D('OrderRoom');
        $orderRoomModel->startTrans();
        $commit = true;

        $orderNumber = $data['orderNumber'];
        $couponGetNo = !empty($data['couponGetNo']) ? $data['couponGetNo'] : null;
        $totalFee = $data['totalFee'];
        $userId = $data['userId'];
        // 获取订单信息,判断是否需要执行修改订单,若需要,执行修改
        $orderRoomId = decodeOrderNumber($orderNumber, 'MZ');

        $orderRoomModel = D('OrderRoom');
        $orderRoom = $orderRoomModel->getInfo($orderRoomId)[0];
        $orderRooms = $orderRoomModel->getInfoByOrder($orderRoom['orderinfo_id'], false);
        $orderRoomIds = array_column($orderRooms, 'id');

        $orderBookLogic = A('Common/OrderBook', 'Logic');
        try {
            // 获取子订单数据 组装数据格式
            $orderDetails = array();
            // 已预订房间数
            $orderBookedRooms = 0;
            $deposit = 0;
            $orderRoomInfo = $orderBookLogic->getOrderDetail($orderRoomId);
            // 获取客栈押金
            $hotelPayDetailModel = D('HotelPayDetail');
            $hotelPayDetail = $hotelPayDetailModel->getInfoByHotel($orderRoomInfo['order']['hotelentity_id']);

            foreach ($orderRoomIds as $key => $orderRoomIdItem) {
                $orderRoomInfos = $orderBookLogic->getOrderDetail($orderRoomIdItem);
                if ($orderRoomInfos['status'] == ORDER_BOOKED) {
                    $orderBookedRooms ++;
                    // 子订单总押金 
                    $deposit += $hotelPayDetail['deposit'];
                    $orderDetailItem = array(
                        'orderRoomId' => $orderRoomInfos['id'],
                        'orderDate' => empty($orderRoomInfos['hour']) ? substr($orderRoomInfos['startdate'], 0, 10) : $orderRoomInfos['startdate'],
                        'roomId' => $orderRoomInfos['roominfo_id'],
                        'nights' => $orderRoomInfos['realnight'],
                        'hour' => $orderRoomInfos['hour'],
                        'payment' => $orderRoomInfos['payment'],
                        'users' => array(),
                    );
                    array_push($orderDetails, $orderDetailItem);
                }
            }
            unset($orderRoomIdItem);

            // 获取客栈默认货币
            $currencyLogic = A('Common/Currency', 'Logic');
            $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($orderRoomInfo['order']['hotelentity_id'], true);
            $currencyId = !empty($hotelDefaultCurrency) ? $hotelDefaultCurrency[0]['currencyId'] : 8 ; // 8 = 人民币

            
            // 子订单共同数据
            if ($orderRoomInfo['status'] == ORDER_BOOKED) {
                $receipt = (double)$totalFee - (double)$deposit;

                // 获取支付宝支付在该客栈的支付方式id
                $hotelLogic = A('Common/Hotel', 'Logic');
                $hotelPay = $hotelLogic->getHotelPay($orderRoomInfo['order']['hotelentity_id'], false, 'zh_cn', true);
                $hotelPay = getArrayValueAsIndex($hotelPay, 'name');
                $hotelPayId = $hotelPay['会员卡']['id'];

                foreach ($orderDetails as $key => &$orderDetailsItem) {
                    foreach ($orderRoomInfo['user'] as $orderUserItem) {
                        array_push($orderDetailsItem['users'], array(
                            'name' => $orderUserItem['name'],
                            'mobile' => $orderUserItem['mobile'],
                            'identity' => $orderUserItem['identity'],
                            'orderUser' => $orderUserItem['id'],
                        ));
                    }
                    unset($orderUserItem);
                }
                unset($orderDetailsItem);

                $receives = array(array(
                    'category' => PAY_CHANGE_RECEIPT,
                    'type' => $hotelPayId,
                    'value' => $receipt,
                    'transBeforeValue' => $receipt,
                    'transCurrencyId' => $currencyId,
                ));
                if ($deposit != 0) {
                    array_push($receives, array(
                        'category' => PAY_CHANGE_DEPOSIT,
                        'type' => $hotelPayId,
                        'value' => $deposit,
                        'transBeforeValue' => $deposit,
                        'transCurrencyId' => $currencyId,
                    ));
                }
                //找出vip信息
                $orderInfoModel = D('OrderInfo');
                $orderVip = $orderInfoModel->getInfo($orderRoomInfo['order']['id'], false);
                $vip['discountRule'] = $orderVip['discountrule'];
                $vip['discount'] = $orderVip['discount'];
                // 预订人为 会员卡信息
                $vipCard = array(
                    'cardMobile' => $orderRoomInfo['order']['mobile'],
                    'cardAreaCode' => $orderRoomInfo['order']['areacode'],
                    'channel' => ORDER_CHANGE_BOOK_WEB,
                    'userId' => $userId,
                );

                $orderLogic = A('Common/Order', 'Logic');
                $payResult = $orderLogic->saveInfo($orderRoomInfo['order']['hotelentity_id'], $orderRoomInfo['order']['id'], $orderRoomInfo['order']['hotelchannel_id'], $deposit, $receipt, null, $orderDetails, $receives, ORDER_CHANGE_BOOK_WEB, $orderRoomInfo['order']['userlogin_id'], 'multiTransMode', $vip, null, null, $vipCard, $couponGetNo);
                if (empty($payResult)) {
                    $commit = false;
                }
            }
        } catch (\Exception $e) {
            $orderRoomModel->rollback();
            return parent::returnJson($e->getMessage());
        }

        if ($commit) {
            $orderRoomModel->commit();
            return parent::returnJson(200, 200);
        } else {
            $orderRoomModel->rollback();
            return parent::returnJson(500, 500);
        }
    }

    /**
     * 用户确认入住
     * @modify trainyao 2016-01-07    创建
     * @modify wenhui 2017-02-20   修改 通过子订单id确认入住 预订人可以办理多房间入住
     * @param array $orderRoomId 子订单id
     * @param int $bookPerson 是否预订人 1：预订人 0：不是预订人
     * @param int $bookUserId 房间拥有者 微预定用户id
     */
    public function checkin($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            //'orderNumber' => 'notnull,notempty,mzOrder',
            'userId' => 'notnull,notempty,id',
            'bookUserId' => 'notnull,notempty,id',
            'bookPerson' => 'notnull,notempty',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $bookUserId = $data['bookUserId'];
        $orderRoomId = $data['orderRoomId'];
        if (!is_array($orderRoomId)) {
            $orderRoomId = explode(',', $orderRoomId);
        }
        $bookPerson = $data['bookPerson'];

        $userId = $data['userId'];
        $orderBookLogic = A('Common/OrderBook', 'Logic');

        foreach ($orderRoomId as $key => $orderRoomIdItem) {
            try {
                $orderInfo = $orderBookLogic->getOrderDetail($orderRoomIdItem);
                 if (count($orderRoomId) >= 1 && $bookPerson == 1) {
                    if ($orderInfo['order']['userlogin_id'] != $userId) {
                        return parent::returnJson(403, 202);
                    }
                 } else {
                    if ($bookUserId != $userId) {
                        return parent::returnJson(403, 202);
                    }
                 }

            } catch (\Exception $e) {
                return parent::returnJson($e->getMessage());
            }

            // 只有支付的订单才能办理入住
            if ($orderInfo['status'] != ORDER_PAYED) {
                return parent::returnJson(403, 202);
            }

            $checkInOrderUserData = array();
            // 办理入住
            $orderLogic = A('Common/Order', 'Logic');
            $checkInOrderUserDataItem = array(
                'value' => $orderInfo['id'],
                'users' => array(),
            );
            foreach ($orderInfo['user'] as $index => $orderUserItem) {
                array_push($checkInOrderUserDataItem['users'], array(
                    'orderUser' => $orderUserItem['id'],
                    'name' => $orderUserItem['name'],
                    'areacode' => $orderUserItem['areacode'],
                    'mobile' => $orderUserItem['mobile'],
                    'areacode' => $orderUserItem['areacode'],
                    'identity' => $orderUserItem['identity'],
                ));
            }
            unset($orderUserItem);
            $checkInOrderUserData = array($checkInOrderUserDataItem);

            try {
                $checkInResult = $orderLogic->checkInOrder($orderInfo['hotelentity_id'], $orderInfo['order']['id'], $orderInfo['id'], ORDER_CHANGE_BOOK_WEB, $checkInOrderUserData, null, null, null, null, null, $userId);
            } catch (\Exception $e) {
                return parent::returnJson($e->getMessage());
                return;
            }
        }

        return parent::returnJson(200, 200);
    }

    /**
     * 用户提前退房
     * @modify trainyao 2016-05-13    创建
     * @modify wenhui 2017-02-20   修改 通过子订单id办理退房 预订人可以办理多房间退房
     * @param array $orderRoomId 子订单id
     * @param int $bookPerson 是否预订人 1：预订人 0：不是预订人
     * @param int $bookUserId 房间拥有者 微预定用户id
     */
    public function checkout($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            //'orderNumber' => 'notnull,notempty,mzOrder',
            'userId' => 'notnull,notempty,id',
            'bookUserId' => 'notnull,notempty,id',
            'bookPerson' => 'notnull,notempty',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        //$orderRoomId = decodeOrderNumber($data['orderNumber'], 'MZ');
        $orderRoomId = $data['orderRoomId'];
        if (!is_array($orderRoomId)) {
            $orderRoomId = explode(',', $orderRoomId);
        }
        $bookPerson = $data['bookPerson'];
        $userId = $data['userId'];
        $bookUserId = $data['bookUserId'];
        $orderBookLogic = A('Common/OrderBook', 'Logic');

        foreach ($orderRoomId as $key => $orderRoomIdItem) {
            try {
                $orderInfo = $orderBookLogic->getOrderDetail($orderRoomIdItem);
                if (count($orderRoomId) >= 1 && $bookPerson == 1) {
                    if ($orderInfo['order']['userlogin_id'] != $userId) {
                        return parent::returnJson(403, 202);
                    }
                } else {
                    if ($bookUserId != $userId) {
                        return parent::returnJson(403, 202);
                    }
                }
                
            } catch (\Exception $e) {
                return parent::returnJson($e->getMessage());
            }

            // 只有入住的订单才能办理退房
            if ($orderInfo['status'] != ORDER_CHECKINED) {
                return parent::returnJson(403, 202);
            }

            // 办理退房
            $orderLogic = A('Common/Order', 'Logic');
            $orderRoomModel = D('OrderRoom');
            $orderRoomModel->startTrans();
            $commit = true;
            
            try {
                $checkoutResult = $orderLogic->checkOutOrder($orderInfo['hotelentity_id'], $orderInfo['order']['id'], $orderInfo['id'], ORDER_CHANGE_BOOK_WEB, $orderInfo['id'], null, null, null, null, null, $userId, 'multiTransMode');
                if (!empty($checkoutResult)) {
                    $orderRefundLogic = A('Common/OrderRefund', 'Logic');
                    $checkoutResult = $orderRefundLogic->refund($orderInfo['hotelentity_id'], $orderInfo['id'], ((double)$orderInfo['order']['receipt'] + (double)$orderInfo['order']['deposit']), '预定端提前退房', REFUND_TYPE_CHECKOUT, $orderInfo['order']['id']);
                }
            } catch (\Exception $e) {
                $commit = false;
                $orderRoomModel->rollback();
                return parent::returnJson($e->getMessage());
                return;
            }

            $orderRoomModel->commit();
        }

        // 保存提前退房 推送消息
        $orderInfo = $orderBookLogic->getOrderDetail($orderRoomId[0]);
        $data = array(
            'name' => $orderInfo['order']['name'],
            'areaCode' => $orderInfo['order']['areacode'],
            'mobile' => $orderInfo['order']['mobile'],
            'night' => $orderInfo['realnight'],
            'id' => $orderInfo['id'],
            'room' => $orderInfo['roominfo_id'],
            'roomtype' => $orderInfo['roomtype_name'],
            'roomname' => $orderInfo['roominfo_name'],
            'order' => $orderInfo['orderinfo_id'],
            'hour' => $orderInfo['hour'],
            'month' => $orderInfo['month'],
            'start' => '',
            'starttime' => '',
            'type' => 1,
        );
        $addResult = $this->addPushInfo($orderInfo['hotelentity_id'], array($data));
        // 执行推送
        if ($addResult == true) {
            $result = $this->pushNewsTask($orderInfo['hotelentity_id'], $orderInfo['roominfo_id']);
        }

        return parent::returnJson(200, 200);
    }

    /**
     * 用户取消订单
     * @modify trainyao 2016-05-13    创建
     */
    public function cancel($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'orderNumber' => 'notnull,notempty,mzOrder',
            'userId' => 'notnull,notempty,id',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $orderRoomId = decodeOrderNumber($data['orderNumber'], 'MZ');

        $orderRoomModel = D('OrderRoom');
        $orderRoom = $orderRoomModel->getInfo($orderRoomId)[0];
        $orderRooms = $orderRoomModel->getInfoByOrder($orderRoom['orderinfo_id'], false);
        $orderRoomIds = array_column($orderRooms, 'id');

        $userId = $data['userId'];
        $orderBookLogic = A('Common/OrderBook', 'Logic');
        foreach ($orderRoomIds as $key => $orderRoomIdItem) {
            try {
                $orderInfo = $orderBookLogic->getOrderDetail($orderRoomIdItem);
                if ($orderInfo['order']['userlogin_id'] != $userId) {
                    return parent::returnJson(403, 202);
                }
            } catch (\Exception $e) {
                return parent::returnJson($e->getMessage());
            }
            // 只有预定的订单才能办理取消订单
            if ($orderInfo['status'] == ORDER_CANCELED) {
                unset($orderRoomIds[$orderRoomIdItem]);
                continue;
            }
            // 只有预定的订单才能办理取消订单
            if ($orderInfo['status'] != ORDER_BOOKED) {
                return parent::returnJson(403, 202);
            }
        }
        if(empty($orderRoomIds)){
            return parent::returnJson(403, 404);
        }
        // 办理退房
        $orderLogic = A('Common/Order', 'Logic');
        try {
            $checkInResult = $orderLogic->cancelOrder($orderInfo['hotelentity_id'], $orderInfo['order']['id'], $orderRoomIds, ORDER_CHANGE_BOOK_WEB, null, null, null, null, null, $userId);
        } catch (\Exception $e) {
            return parent::returnJson($e->getMessage());
            return;
        }

        return parent::returnJson(200, 200);
    }

    /**
     * 用户申请退款
     * @modify trainyao 2016-05-13    创建
     */
    public function refund($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'orderNumber' => 'notnull,notempty,mzOrder',
            'userId' => 'notnull,notempty,id',
            'reason' => 'notnull,notempty,nameLength50',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $orderRoomId = decodeOrderNumber($data['orderNumber'], 'MZ');
        $userId = $data['userId'];
        $orderBookLogic = A('Common/OrderBook', 'Logic');
        try {
            $orderInfo = $orderBookLogic->getOrderDetail($orderRoomId);
            if ($orderInfo['order']['userlogin_id'] != $userId) {
                return parent::returnJson(403, 202);
            }
        } catch (\Exception $e) {
            return parent::returnJson($e->getMessage());
        }

        // 只有支付的订单才能办理退款
        if ($orderInfo['status'] != ORDER_PAYED) {
            return parent::returnJson(403, 123);
        }

        // 办理退款申请
        $reason = $data['reason'];
        $orderRefundLogic = A('Common/OrderRefund', 'Logic');
        $orderLogic = A('Common/Order', 'Logic');
        try {
            $refundPrice = (double)$orderInfo['order']['receipt'] + (double)$orderInfo['order']['deposit'];
            $refundResult = $orderRefundLogic->refund($orderInfo['hotelentity_id'], $orderRoomId, $refundPrice, $reason);
        } catch (\Exception $e) {
            return parent::returnJson($e->getMessage());
            return;
        }

        return parent::returnJson(200, 200);
    }

    /**
     * @description  获取身份证数据
     * @modify wenhui 2016-06-19
     */
    public function getOrderUserInfo($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }

        $validateRule = array(
            'hotel' => 'notnull,notempty',
            'identity' => 'notnull',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $orderInfoModel = D('OrderInfo');
        $orderInfos = $orderInfoModel->getInfoByHotelAndDate($data['hotel']);
        $orderInfoIdAll = array_column($orderInfos, 'id');

        $orderUserModel = D('OrderUser');
        $orderUserInfo = $orderUserModel->getInfoByIdentity($data['identity'], $orderInfoIdAll);
        if (empty($orderUserInfo['identity'])) {
            return parent::returnJson(200, 200, array());
        }

        // 组装数据
        unset($orderUserInfo['id']);
        unset($orderUserInfo['orderinfo_id']);
        unset($orderUserInfo['userlogin_id']);
        unset($orderUserInfo['areacode']);
        unset($orderUserInfo['mobile']);
        unset($orderUserInfo['isdelete']);

        return parent::returnJson(200, 200, $orderUserInfo);
    }

    /**
     * @description 修改订单
     * @modify wenhui 2017-10-10 创建
     */
    public function saveOrder($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }

        $validateRule = array(
            'orderUserId' => 'notnull,notempty,id',
            'name' => 'notnull',
            'identity' => 'notnull',
            'idsex' => 'notnull',
            'idnation' => 'notnull',
            'idaddress' => 'notnull',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $orderUserId = $data['orderUserId'];
        $name = $data['name'];
        $identity = $data['identity'];
        $idsex = $data['idsex'];
        $idnation = $data['idnation'];
        $idaddress = $data['idaddress'];

        $orderUserModel = D('OrderUser');
        $saveResult = $orderUserModel->saveInfo($orderUserId, '', null, null, $name, $identity, null, $idsex, $idnation, $idaddress);
        if ($saveResult) {
            return parent::returnJson(200, 200);
        }

        return parent::returnJson(500, 506);
    }

    /**
     * 获取用户有效订单或历史订单
     * @modify trainyao 2016-01-11    创建
     * @modify wenhui 2017-02-20    修改 以子订单id获取订单 修改返回数据格式
     * @param intetger $userId 预定用户ID
     * @param intetger $status 0=有效订单,1=历史订单
     */
    public function getTotalCharity($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }
        $userId = $data['userId'];

        $orderUserModel = D('OrderUser');
        $orderUserInfo = $orderUserModel->getInfoByUserId($userId);
        $orderInfoIds = array_column($orderUserInfo, 'orderinfo_id');
        $orderInfoModel = D('OrderInfo');
        $orderInfos = $orderInfoModel->getInfoByOrderAndDate(['in',$orderInfoIds], null, null, ['in',[1,2,3,4]], true);

        // 处理数据
        $data = array();
        $totalCharity = 0;
        foreach ($orderInfos as $key => $orderItem) {
            $totalCharity += $orderItem['charityprice'];
        }
        unset($orderItem);

        $data['totalCharity'] = $totalCharity;
        return parent::returnJson(200, 200, $data);
    }

    /**
     * 是否开启支付方式 (是否线下付)
     * @modify wenhui 2017-11-30    创建
     * @param intetger $hotelId 客栈id
     * @param bool $qrclietBook 是否从钥匙包进入
     * @param bool $isWechatBrowser 是否微信浏览器
     */
    private function isOffline ($hotelId, $qrclietBook, $isWechatBrowser) {
        $hotelPayDetailModel = D('HotelPayDetail');
        $hotelPayUsableModel = D('HotelPayUsable');

        $hotelPayDetail = $hotelPayDetailModel->getInfoByHotel($hotelId);
        $hotelPayUsableInfo = $hotelPayUsableModel->getInfo($hotelId);
        $currentDate = date('Y-m-d');
        $enablepay = false;
        if (($hotelPayUsableInfo['uclbrtalipayenable'] == 1 && $hotelPayUsableInfo['uclbrtalipayenddate'] >= $currentDate) || ($hotelPayUsableInfo['uclbrtwechatenable'] == 1 && $hotelPayUsableInfo['uclbrtwechatenddate'] >= $currentDate) || ($hotelPayUsableInfo['hotelalipayenable'] == 1 && $hotelPayUsableInfo['hotelalipayenddate'] >= $currentDate) || ($hotelPayUsableInfo['hotelwechatenable'] == 1 && $hotelPayUsableInfo['hotelwechatenddata'] >= $currentDate)) {
            $enablepay = true;
        }

        $isOffline = true;
        if (!empty($hotelPayDetail['type']) && $hotelPayDetail['type']>0 && $enablepay){
            $isOffline = false;
        }

        // 从钥匙包进入 没有商家微信自收
        if ($qrclietBook == true) {
            if (!empty($hotelPayDetail['type']) && $hotelPayDetail['type'] == 32 && $enablepay) {
                $isOffline = true;
            }
        }

        // 是否微信浏览器
        if (!$isWechatBrowser && !$qrclietBook) {
            if (!empty($hotelPayDetail['type']) && in_array($hotelPayDetail['type'], [2,32]) && $enablepay) {
                $isOffline = true;
            }
        }

        if (!empty($hotelPayDetail['type']) && in_array($hotelPayDetail['type'], [64,65,66,67,80,82,96,97,112])){
            $isOffline = false;
        }

        $currencyLogic = A('Common/Currency', 'Logic');
        $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($hotelId, true);
        // 默认货币不是人民币的客栈 则线下付 // 8 = 人民币
        if (!empty($hotelDefaultCurrency) && $hotelDefaultCurrency[0]['currencyId'] != 8) {
            $isOffline = true;
        }

        return $isOffline;
    }

    /**
     * 获取并过滤优惠券数据
     * @modify wenhui 2017-11-30    创建
     * @param array $couponId 优惠券Id
     * @param array $roomTypeId 当前房型Id
     * @param bool $isVipUser 是否会员
     */
    private function getAndFilterCouponData ($couponId, $roomTypeId = null, $isVipUser = null) {
        $hotelCouponModel = D('HotelCoupon');
        $hotelCouponRoomTypeModel = D('HotelCouponRoomType');
        $hotelCouponDisableDateModel = D('HotelCouponDisableDate');

        $couponData = $hotelCouponModel->getCouponByIds($couponId);
        $couponRoomTypeData = $hotelCouponRoomTypeModel->getCouponRoomType($couponId);
        $roomTypeIdArray = array_column($couponRoomTypeData, 'roomtype_id');

        $couponDisableDate = $hotelCouponDisableDateModel->getCouponDisableDate($couponId);
        $couponDateArray = array_column($couponDisableDate, 'date');

        $currentWeek = date('w');
        $currentStamp = strtotime(date('Y-m-d'));
        // 条件过滤
        foreach ($couponData as $key => $coupon) {
            // 是否会员
            if (!is_null($isVipUser)) {
                if ($isVipUser) {
                    // 会员 返回全部和会员优惠券
                    if (!in_array($coupon['crowd'], [COUPON_ALL_USER, COUPON_VIP_USER])) {
                        unset($couponData[$key]);
                        continue;
                    }
                } else {
                    // 非会员  返回全部和非会员优惠券
                    if (!in_array($coupon['crowd'], [COUPON_ALL_USER, COUPON_NOT_VIP_USER])) {
                        unset($couponData[$key]);
                        continue;
                    }
                }
            }

            // 房间类型 1=间夜房 2=钟点房 3=长租房
            if (!in_array($coupon['roomtype'], [1])) {
                unset($couponData[$key]);
                continue;
            }

            // 是否优惠券房型
            if (!is_null($roomTypeId) && !in_array($roomTypeId, $roomTypeIdArray)) {
                unset($couponData[$key]);
                continue;
            }

            // 过滤不可用星期
            $couponWeekArray = explode(',', $coupon['week']);
            if (in_array($currentWeek, $couponWeekArray)) {
                unset($couponData[$key]);
                continue;
            }

            // 过滤不可用日期
            if (in_array($currentStamp, $couponDateArray)) {
                unset($couponData[$key]);
                continue;
            }

            // 过滤不在有效期的优惠券
            if (!isBetweenTime($currentStamp, $coupon['startdate'], $coupon['enddate'])) {
                unset($couponData[$key]);
                continue;
            }
        }
        unset($coupon);

        return $couponData;
    }
}
